package main

import (
	"arc_srv4/common"
	"arc_srv4/database"
	"arc_srv4/logutils"
	"arc_srv4/middleware"
	"arc_srv4/routes"
	"arc_srv4/utils"
	"github.com/betacraft/yaag/yaag"
	prometheusMiddleware "github.com/iris-contrib/middleware/prometheus"
	"github.com/iris-contrib/swagger/v12"
	"github.com/iris-contrib/swagger/v12/swaggerFiles"
	"github.com/kataras/iris/v12"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	//prometheusMiddleware "github.com/iris-contrib/middleware/prometheus"
	//"github.com/prometheus/client_golang/prometheus"
)

func initDevice() {
	// 初始化日志
	_ = logutils.InitLogger()
	logutils.Logger.Info("log init success......")

	// 初始化配置
	common.InitConfig()
	logutils.Logger.Info("config init success......")

	// 初始化数据库
	database.InitMysql()
	logutils.Logger.Info("database init success......")

	// 初始化redis
	_ = utils.InitRedis()
	logutils.Logger.Info("redis init success......")

	// 从redis加载人脸数据，先删除后添加（此程序用的redis单程序池，不能用于集群）
	utils.RedisDeleteFace()
	utils.LoadFaceData()
	// 初始化一个测试账号
	//_ = srv.GenNewKey("mk","12345678901","XXXXXX公司",1)

	//go utils.SendEmailSys("人脸识别引擎启动成功")
}

func newApp() (api *iris.Application) {
	api = iris.New()

	// Prometheus
	p := prometheusMiddleware.New("127.0.0.1", 300, 1200, 5000)
	api.Use(p.ServeHTTP)
	api.OnErrorCode(iris.StatusNotFound, func(ctx iris.Context) {
		p.ServeHTTP(ctx)
		_, _ = ctx.Writef("Not Found")
	})

	// 中间件
	api.Use(middleware.Trace)
	// 注册路由
	routes.Register(api)

	//api 文档配置
	yaag.Init(&yaag.Config{ // <- IMPORTANT, init the middleware.
		On:       true,
		DocTitle: common.AppConCfg.Name,
		DocPath:  common.AppConCfg.Doc + "/index.html", //设置绝对路径
		BaseUrls: map[string]string{
			"URL":  common.AppConCfg.Url,
			"生成时间": "2020-06-23",
		},
	})

	// swagger 中间件
	// 访问地址 url/swagger/index.html
	config := &swagger.Config{
		URL: common.AppConCfg.Url + "/swagger/doc.json",
	}
	api.Get("/swagger/{any:path}", swagger.CustomWrapHandler(config, swaggerFiles.Handler))
	return
}

func main() {
	initDevice()
	app := newApp()
	app.RegisterView(iris.HTML("./", ".html"))
	app.HandleDir("/apidoc", "./apidoc")
	app.Get("/metrics", iris.FromStd(promhttp.Handler()))

	addr := common.AppConCfg.Addr
	_ = app.Run(iris.Addr(addr), iris.WithoutServerError(iris.ErrServerClosed))

	logutils.Logger.Info("server start at " + addr)
}
